import psycopg
from psycopg import OperationalError, IntegrityError

def get_connection():
    try:
        return psycopg.connect(
            dbname="hospital-management",  # 更新为你的数据库名称
            user="postgres",              # 你的用户名
            password="Xu120697",          # 你的密码
            host="localhost",
            port="5432"
        )
    except OperationalError as e:
        raise ConnectionError(f"Database connection failed: {e}")

def execute_query(query, params=None, fetch=False, fetchone=False):
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(query, params or ())
            if fetch:
                return cur.fetchall()
            elif fetchone:
                return cur.fetchone()
            conn.commit()
    except IntegrityError as e:
        conn.rollback()
        raise ValueError(f"Integrity error (constraint violation): {e}")
    except Exception as e:
        conn.rollback()
        raise RuntimeError(f"Query execution failed: {e}")
    finally:
        conn.close()